package oom;
import java.lang.reflect.Field;

import sun.misc.Unsafe;
/**
 * 由DirectMemory导致的内存溢出
 * 虽然使用DirectByteBuffer分配内存也会抛出内存溢出异常，但他抛出异常时并没有真正向操作系统申请分配内存
 * 而是通过计算得知内存无法分配，于是手动抛出异常，真正申请分配内存的方法是unsafe.allocateMemory()
 * -Xmx20M -XX:MaxDirectMemorySize=10M 
 * @author Ditto
 *
 */
public class DirectMemoryOOM {

	private static final int _1MB=1024*1024;
	
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
		Field unsafeField = Unsafe.class.getDeclaredFields()[0];
		unsafeField.setAccessible(true);
		Unsafe unsafe = (Unsafe) unsafeField.get(null);
		while(true){
			unsafe.allocateMemory(_1MB);
		}
	}
}
